//加载公共样式
require('../../assets/css/index.less')

//加载自己的样式
require('./reg.less')

//1 引入验证码插件
const CaptchaMini = require('captcha-mini')

//导入请求实例
const request = require('../../utils/request')

//dom加载完毕
window.onload = () => {
  //获取dom
  const phoneIpt = document.querySelector('#phoneIpt')
  const codeIpt = document.querySelector('#codeIpt')
  const pwdIpt = document.querySelector('#pwdIpt')
  const pwdTwiceIpt = document.querySelector('#pwdTwiceIpt')
  const submit = document.querySelector('#submit')

  /*不传值，统一走默认值*/
  //2 创建验证码实例对象 配置字体大小
  let captcha1 = new CaptchaMini({
    fontSize: 60, //字体大小
    dotNum: 100, //点的数量
    length: 4, //验证码长度
  })
  //3 画图
  let captcha = '' //存储验证码 给提交表单用
  captcha1.draw(document.querySelector('#code'), r => {
    //打印验证码
    captcha = r
    console.log(r, '验证码1')
  })

  //点击注册按钮
  submit.addEventListener('click', () => {
    //收集错误信息
    let errMsg = ''
    //开始验证
    if (!/^1[3-9]\d{9}$/.test(phoneIpt.value)) {
      errMsg = '手机号格式不正确'
      //验证码全部转为小写 方便用户
    } else if (codeIpt.value.toLowerCase() !== captcha.toLowerCase()) {
      errMsg = '验证码错误'
    } else if (!/^\w{3,6}$/.test(pwdIpt.value)) {
      errMsg = '密码3-6位'
    } else if (pwdIpt.value !== pwdTwiceIpt.value) {
      errMsg = '密码不一致'
    } else {
      console.log('验证通过 可以发送请求')

      //发送请求检测 账号是否存在
      request
        .post('/api/user/isExist', {
          account: phoneIpt.value,
        })
        .then(res => {
          console.log('res :>> ', res)
          //解构数据
          let {errno, message} = res.data
          //判断
          if (errno === 0) {
            //发送请求
            request.post('/api/user/register',{
              account: phoneIpt.value,
              password: pwdIpt.value
            })
            /* 解构 */
            .then(res=>{
             let {data,errno}=res.data;
             if(errno===0){
              alert('注册成功')
              location.href='../login.html'
             }

            })


          } else {
            alert(message)
          }
        })
        .catch(err => {
          console.log('err :>> ', err)
        })
    }

    if (errMsg) {
      alert(errMsg)
    }
  })
}
